
# look at Mark Hammond's Win32all? There is a module called 
# win32evtlog that you can use to dump the windows eventlogs.
# http://mail.python.org/pipermail/python-list/2003-December/239568.html

import win32evtlog, win32security
from win32evtlogutil import *
import sys
import re

rsn = lambda x: re.sub('\n', '', x)

def ReadLog(computer, logType="Application", dumpEachRecord = 0):
     # read the entire log back.
     h=win32evtlog.OpenEventLog(computer, logType)
     numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
     print "There are %d records" % numRecords

     num=0
     while 1:
         objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
         if not objects:
             break
         for object in objects:
             # get it for testing purposes, but dont print it.
             msg = SafeFormatMessage(object, logType).encode("mbcs")
             if object.Sid is not None:
                 try:
                     domain, user, typ = win32security.LookupAccountSid(computer, object.Sid)
                     sidDesc = "%s/%s" % (domain, user)
                 except win32security.error:
                     sidDesc = str(object.Sid)
                 user_desc = "Event associated with user %s" % (sidDesc,)
             else:
                 user_desc = None
             if dumpEachRecord:
                 if user_desc:
                     print "::UDESC::%s"%rsn(user_desc)
                 print "::MSG::%s"%rsn(msg)
         num = num + len(objects)

     if numRecords == num:
         print "Successfully read all", numRecords, "records"
     else:
         print "Couldn't get all records - reported %d, but found %d" % (numRecords, num)
         print "(Note that some other app may have written records while we were running!)"
     win32evtlog.CloseEventLog(h)

#logTypes = ["Application", "Security", "System"]
logTypes = ["Security"]
#logTypes = ["Security", "System"]

for logType in logTypes:
    ## redirect stdo to file
    sys.stdout = open('dump-win-logs_' + logType + '.log', 'w')

    computer = None # use local machine
    verbose = 1
    ReadLog(computer, logType, verbose > 0)

    ## close and redirect stdo back to normal
    sys.stdout=sys.__stdout__
